package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0018.java
 * @Author : WangRuoyu
 * @Date 2023/11/8 22:37
 */


public class Q0018 {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length < 4) return res;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int l = j + 1;
                int r = nums.length - 1;
                while (l < r) {
                    long tmp = (long) nums[i] + (long) nums[j] + (long) nums[l] + (long) nums[r];
                    if (tmp == (long) target) {
                        ArrayList<Integer> ans = new ArrayList<>();
                        ans.add(nums[i]);
                        ans.add(nums[j]);
                        ans.add(nums[l]);
                        ans.add(nums[r]);
                        res.add(ans);
                        l++;
                        while (l < r && nums[l] == nums[l - 1]) l++;
                        r--;
                        while (r > l && nums[r] == nums[r + 1]) r--;
                    } else if (tmp < target) {
                        l++;
                    } else {
                        r--;
                    }
                }
            }
        }
        return res;
    }
    public static void main(String[] args) {
        Q0018 sl = new Q0018();
        int[] nums = {1000000000, 1000000000, 1000000000, 1000000000};
        int target = -294967296;
        System.out.println(sl.fourSum(nums, target));
    }
}